package com.zut.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;

import java.io.FileInputStream;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.Month;
import java.util.UUID;

/**
 * @author 张晨
 * @date 2024/9/11 16:48
 * @desc
 */
public class AliOssUtil {
    public static String upload(InputStream inputStream,String objectName) {
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-beijing.aliyuncs.com";
        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        // EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        DefaultCredentialProvider defaultCredentialProvider = CredentialsProviderFactory.newDefaultCredentialProvider("LTAI5tKZQ7joWWRKQE9616SH", "qNY3SoMkcu8sRymTK7DD0ZK71QchAX");
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "neusoft-tjjava04";
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        // String objectName = "1.jpg";
        // 填写本地文件的完整路径，例如D:\\localpath\\examplefile.txt。
        // 如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件流。
        // String filePath = "F:\\java03\\Vue.js/workspace1/ele-UI/src/views/business/logo.png";

        String str1 = objectName.substring(objectName.lastIndexOf("."));
        LocalDate now = LocalDate.now();
        String year =now.getYear()+"";
        String monthValue = now.getMonthValue()+"";
        String dayOfMonth = now.getDayOfMonth()+"";
        // String uuid = UUID.randomUUID().toString();

        objectName = year+"/"+monthValue+"/"+dayOfMonth+"/"+System.currentTimeMillis()+str1;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, defaultCredentialProvider);

        try {
            // InputStream inputStream = new FileInputStream(filePath);
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
            // 创建PutObject请求。
            PutObjectResult result = ossClient.putObject(putObjectRequest);

            return "https://"+bucketName+".oss-cn-beijing.aliyuncs.com/"+objectName;


        } catch (Exception ce) {
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;
    }
}
